<template>
  <a-card :bordered="false">
    <h3>抽奖活动列表</h3>
    <MemberPromotionsFilter ref="filter" @onAdd="handleAddOrEdit" :brandList="brandList" @onSearch="onSearch"></MemberPromotionsFilter>
    <a-tabs v-model="activeKey" @change="tabChange">
      <a-tab-pane v-for="item in tabList" :tab="item.name" :key="item.status"> </a-tab-pane>
    </a-tabs>
    <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }">
      <span slot="image" slot-scope="text, record">
        <img class="img" :src="record.backPicture" alt="">
      </span>
      <span slot="content" slot-scope="text, record">
          <p>{{record.name}}</p>
          <p>活动时间：{{record.startTime}}~{{record.endTime}}</p>
          <p>归属微商城：{{record.appName}}</p>
          <p style="font-weight: bold;">浏览人数：{{record.browseNumber | filNum}}   抽奖人数：{{record.drawNumber | filNum}}</p>
      </span>
      <span slot="action" slot-scope="record">
        <a-button class="btn" style="min-width: 90px;" @click="handleCopyLuckyDrawById(record.id)">复制活动</a-button>
        <a-button class="btn" v-if="activeKey != 3" style="min-width: 90px;" @click="handleAddOrEdit(record.id)">编辑活动</a-button>
        <a-button class="btn" style="min-width: 90px;" @click="winningList(record.id)">中奖记录</a-button>
        <a-popconfirm title="确定删除抽奖活动吗？" ok-text="确定" cancel-text="暂不" @confirm="handleDeleteLuckyDrawInfo(record.id)">
          <a-button class="btn" style="min-width: 90px;" v-if="activeKey == 3">删除</a-button>
        </a-popconfirm>
        <a-popconfirm title="确定结束抽奖活动吗？" ok-text="确定" cancel-text="暂不" @confirm="handleCloseLuckyDraw(record.id)">
          <a-button style="min-width: 90px;" v-if="activeKey == 1" class="btn">立即结束</a-button>
        </a-popconfirm>
        <a-popconfirm title="确定开始抽奖活动吗？" ok-text="确定" cancel-text="暂不" @confirm="handleStartLuckyDrawById(record.id)">
          <a-button style="min-width: 90px;" v-if="activeKey == 2" class="btn">立即开始</a-button>
        </a-popconfirm>
        
        <a-button style="min-width: 90px;" v-if="activeKey != 3" class="btn" @click="handleOpenPromotionModal(record)">投放</a-button>
        <a-button style="min-width: 90px;" class="btn" @click="handleOperation(record.id)">运维</a-button>
      </span>
    </s-table>

    <a-modal title="投放" :visible="visible" width="600px" :footer="null" @cancel="visible = false, promotionQRcode='', record={}, appId = '', luckyId=''">
      <a-form-item label="小程序路径">
        {{url}}?luckyId={{luckyId}}
      </a-form-item>
      <a-form-item label="小程序码">
        <a-select v-model="appId" style="width: 80%;" placeholder="请选择" show-search :filter-option="filterOption">
          <a-select-option :value="item.appid" v-for="(item, index) in promotionBrandList" :key="index"> {{ item.name }}微商城 </a-select-option>
        </a-select>
        <a-button style="margin-left: 10px;" type="primary" @click="handlePromotion">生成</a-button>
      </a-form-item>
      <img v-if="promotionQRcode" :src="promotionQRcode" alt="太阳码" style="width: 200px;height: 200px;">
      <div v-else style="width: 200px;height: 200px;text-align: center;line-height: 200px;">
      </div>
      <p style="margin-top: 5px">*请选择小程序生成对应小程序的抽奖页太阳码</p>
    </a-modal>
  </a-card>
</template>
<script>
import { luckyDrawPageBaseInfo, closeLuckyDrawById, createPromotionQRcode, 
  deleteLuckyDrawInfo, copyLuckyDrawById, startLuckyDrawById, getCountStateNum, getAppShopVoList } from '@/api/marketingCenter/luckyDraw'
import { STable } from '@/views/box/components'
import MemberPromotionsFilter from '../../components/memberPromotionsFilter'
const tabList = [ //1进行中2未开始3已结束
  {
    name: '进行中',
    status: '1'
  },
  {
    name: '未开始',
    status: '2'
  },
  {
    name: '已结束',
    status: '3'
  }
]
const columns = [
  {
    title: '图片',
    width: '120px',
    align: 'center',
    scopedSlots: { customRender: 'image' }
  },
  {
    title: '内容',
    width: '500px',
    scopedSlots: { customRender: 'content' }
  },
  {
    title: '操作',
    width: '330px',
    align: 'right',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {
    MemberPromotionsFilter,
    STable
  },
  data() {
    return {
      appId: '',
      record: {},
      luckyId: '',
      brandList: [],
      visible: false,
      promotionQRcode: '',
      url: 'packages/wm-cloud-jnbytools/luckyDraw/index',
      tabList,
      activeKey: tabList[0].status,
      columns,
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      queryParam: {},

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        if (this.requestFlag()) return
        const data = {
          "state": this.activeKey,
          "current": parameter.pageNo,
          "size": parameter.pageSize,
          ...this.queryParam
        }
        this.getCount(data)
        return luckyDrawPageBaseInfo(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  filters: {
    filNum(v) {
      return v >= 0 ? v : 0
    }
  },
  activated() {
  },
  created() {
    this.getBrandList()
  },
  computed: {
    promotionBrandList() {
      const { appId } = this.record
      console.log(appId, 'appIdxxxx')
      if (!appId) return []
      const list = this.brandList.filter(e => appId.split(',').includes(e.appid))
      return list
    }
  },
  mounted() {},
  watch: {
    $route(to, from) {
      const whiteList = [
        '/marketingCenter/memberPromotions/luckyDraw/addOrEditBasic',
       '/marketingCenter/memberPromotions/luckyDraw/addOrEditShare',
       '/marketingCenter/memberPromotions/luckyDraw/addOrEditSetUp',
       '/marketingCenter/memberPromotions/luckyDraw/winningList',
       '/marketingCenter/memberPromotions/luckyDraw/operation'
       ]
      const currentPathBase = '/marketingCenter/memberPromotions/luckyDraw/luckDrawList'
      const currentPath = this.$route.path
      if (this.checkRoute(from.path, whiteList) && to.path.includes(currentPathBase)) {
        this.$refs.table.refresh() // 刷新当前列表（记录上次页码）
      } else {
        if (currentPath.includes(currentPathBase)) {
          this.activeKey = this.tabList[0].status
          this.tabChange(this.activeKey) // 刷新当前页面
        }
      }
    }
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    requestFlag() {
      const currentPathBase = '/marketingCenter/memberPromotions/luckyDraw/luckDrawList'
      const currentPath = this.$route.path
      if (!currentPath.includes(currentPathBase)) return true
      return false
    },

    // 获取微商城
    getBrandList() {
      if (this.requestFlag()) return
      getAppShopVoList().then(res => {
          if (res.code === 200) {
            this.brandList = res.data
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
    },

    // 获取状态数量
    getCount(data) {
      getCountStateNum(data).then(res => {
        if (res.code === 200) {
          const { beginCount, endCount, unplayedCount } = res.data
          this.tabList[0].name = `进行中（${beginCount || 0}）`
          this.tabList[1].name = `未开始（${unplayedCount || 0}）`
          this.tabList[2].name = `已结束（${endCount || 0}）`
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 立即结束
    handleCloseLuckyDraw(luckyId) {
      const data = {
        luckyId
      }
      closeLuckyDrawById(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 立即开始
    handleStartLuckyDrawById(luckyId) {
      const data = {
        luckyId
      }
      startLuckyDrawById(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    

    // 删除
    handleDeleteLuckyDrawInfo(luckyId) {
      const data = {
        luckyId
      }
      deleteLuckyDrawInfo(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },
    

    // 复制
    handleCopyLuckyDrawById(luckyId) {
      const data = {
        luckyId
      }
      copyLuckyDrawById(data).then(res => {
        if (res.code === 200) {
          const {id} = res.data
          this.$router.push(`/marketingCenter/memberPromotions/luckyDraw/addOrEditBasic/${id}`)
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 打开投放弹窗
    handleOpenPromotionModal(record) {
      this.record = record
      this.luckyId = record.id
      this.visible = true
    },

    // 投放
    handlePromotion() {
      if (!this.appId) {
        this.$message.info('请选择对应的小程序！')
        return
      }
      const data = {
        appId: this.appId,
        luckyId: this.luckyId,
        url: this.url
      }
      createPromotionQRcode(data).then(res => {
        if (res.code === 200) {
          this.promotionQRcode = 'data:image/png;base64,'+res.data
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },
    

    // 查看更多发送对象
    handleShowMember(id) {
      this.id = ''
      const data = {
        id,
        current: 1
      }
      advicesDetail(data).then(res => {
        if (res.code == 200) {
          this.memberVisible = true
          this.id = id
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 新增编辑活动
    handleAddOrEdit(v) {
      this.$router.push(`/marketingCenter/memberPromotions/luckyDraw/addOrEditBasic/${v}`)
    },

    // 运维
    handleOperation(id) {
      this.$router.push(`/marketingCenter/memberPromotions/luckyDraw/operation/${id}`)
    },


    // 中奖记录
    winningList(id) {
      this.$router.push(`/marketingCenter/memberPromotions/luckyDraw/winningList/${id}`)
    },

    tabChange(activeKey) {
      this.$nextTick(() => {
        this.activeKey = activeKey
        this.$refs.filter.reset()
      })
    },

    checkRoute(fromPath, routeArr) {
      for (let i = 0; i < routeArr.length; i++) {
        if (fromPath.includes(routeArr[i])) {
          return true
        }
      }
      return false
    },

    //查询
    onSearch(obj) {
      this.queryParam = obj
      this.$refs.table.refresh(true)
    },

    handleSubmitSort() {}
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-tabs-bar {
  margin-bottom: 0;
}

.img {
  display: block;
  margin: 0 auto;
  width: 120px;
  height: 120px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
}
.btn{
  margin: 4px;
}
</style>
